package com.bear.fastrepair.http.client

import android.util.Log
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import okhttp3.Headers
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitManager {
    private val level: HttpLoggingInterceptor.Level = HttpLoggingInterceptor.Level.BODY
    private val loggingInterceptor = HttpLoggingInterceptor { message ->
        Log.i(javaClass.simpleName, "request message is $message")
    }.apply { level = this@RetrofitManager.level }

    /**
     * 获取一个Retrofit
     * @param url String
     * @param service Class<T>
     * @param headersCallback Function1<Headers, Unit>?
     * @return T
     */
    fun <T> getService(
        url: String,
        service: Class<T>,
        headersCallback: ((Headers) -> Unit)? = null
    ): T {
        //根据你传的service来进行不同的请求
        return createRetrofit(url, headersCallback).create(service)
    }

    /**
     * 获取Retrofit并拦截设置Cookie
     * @param url String
     * @param service Class<T>
     * @param headers Headers?
     * @return T
     */
    fun <T> getServiceSetCookie(url: String, service: Class<T>, headers: Headers? = null): T {
        return createRetrofitSetCookie(url, headers).create(service)
    }

    /**
     * 携带token进行请求
     * @param url String
     * @param service Class<T>
     * @param token String
     * @return T
     */
    fun <T> getServiceSetToken(url: String, service: Class<T>, token: String): T {
        return createRetrofitWithToken(url, token).create(service)
    }

    /**
     *
     * @param url String
     * @param headersCallback Function1<Headers, Unit>?
     * @return Retrofit
     */
    private fun createRetrofit(url: String, headersCallback: ((Headers) -> Unit)?): Retrofit {
        val headerCallbackInterceptor = Interceptor {
            val response = it.proceed(it.request())
            headersCallback?.invoke(response.headers)
            return@Interceptor response
        }

//        return buildRetrofit(url, loggingInterceptor, headerCallbackInterceptor)
        return buildRetrofit(url, headerCallbackInterceptor)
    }

    /**
     * 拦截设置Cookie并创建Retrofit
     * @param url String
     * @param headers Headers?
     * @return Retrofit
     */
    private fun createRetrofitSetCookie(url: String, headers: Headers?): Retrofit {
        val setCookieInterceptor = Interceptor {
            val builder = it.request().newBuilder()
            val cookie =
                headers?.get("Set-Cookie") ?: return@Interceptor it.proceed(builder.build())
            val sessionIdStr = "JSESSIONID="
            if (cookie.contains(sessionIdStr)) {
                val start = cookie.indexOf(sessionIdStr)
                val end = cookie.indexOf(";")
                val sessionId = cookie.substring(start, end)
                Log.i(javaClass.simpleName, "createRetrofitSetCookie: sessionId is $sessionId")
                builder.addHeader("Cookie", sessionId)
            }
            return@Interceptor it.proceed(builder.build())
        }

//        return buildRetrofit(url, loggingInterceptor, setCookieInterceptor)
        return buildRetrofit(url, setCookieInterceptor)
    }

    /**
     * 拦截设置Token并创建Retrofit
     * @param url String
     * @param token String
     * @return Retrofit
     */
    private fun createRetrofitWithToken(url: String, token: String): Retrofit {
        val setTokenInterceptor = Interceptor {
            val builder = it.request().newBuilder()
            builder.header("token", token)
            return@Interceptor it.proceed(builder.build())
        }
//        return buildRetrofit(url, loggingInterceptor, setTokenInterceptor)
        return buildRetrofit(url, setTokenInterceptor)
    }

    private fun buildRetrofit(url: String, vararg interceptors: Interceptor): Retrofit {
        val okHttpClientBuilder = OkHttpClient.Builder()
        //连接超时
        okHttpClientBuilder.connectTimeout(30, TimeUnit.SECONDS)
        //读取超时
        okHttpClientBuilder.readTimeout(10, TimeUnit.SECONDS)
        //添加拦截器
        interceptors.forEach {
            okHttpClientBuilder.addInterceptor(it)
        }
        //创建retrofit对象
        return Retrofit.Builder()
            .baseUrl(url)
            .client(okHttpClientBuilder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
}